<template>
  <div class="user-profile">
    <el-card class="page-header-card">
      <div class="page-header">
        <div class="page-title">
          <h2>个人信息</h2>
          <p>管理您的个人资料和车辆信息</p>
        </div>
      </div>
    </el-card>
    
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="6">
        <!-- 基本信息卡片 -->
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>个人资料</span>
              <el-button 
                type="primary" 
                @click="editMode = !editMode" 
                circle 
                :icon="editMode ? 'Close' : 'Edit'"
              ></el-button>
            </div>
          </template>
          
          <div class="avatar-container">
            <el-avatar :src="AppConfig.defaultAvatar" :size="100"></el-avatar>
          </div>
          
          <div v-if="!editMode" class="info-list">
            <div class="info-item">
              <span class="info-label">用户名</span>
              <span class="info-value">{{ userProfile.username }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">真实姓名</span>
              <span class="info-value">{{ userProfile.realName }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">手机号码</span>
              <span class="info-value">{{ userProfile.phone }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">电子邮箱</span>
              <span class="info-value">{{ userProfile.email }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">注册时间</span>
              <span class="info-value">{{ userProfile.createdAt }}</span>
            </div>
          </div>
          
          <el-form 
            v-else 
            ref="profileFormRef" 
            :model="profileForm" 
            :rules="profileRules"
            label-position="top"
          >
            <el-form-item prop="realName" label="真实姓名">
              <el-input v-model="profileForm.realName" placeholder="请输入真实姓名"></el-input>
            </el-form-item>
            <el-form-item prop="phone" label="手机号码">
              <el-input v-model="profileForm.phone" placeholder="请输入手机号码"></el-input>
            </el-form-item>
            <el-form-item prop="email" label="电子邮箱">
              <el-input v-model="profileForm.email" placeholder="请输入电子邮箱"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="updateProfile" :loading="profileLoading">保存</el-button>
              <el-button @click="editMode = false">取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        
        <!-- 修改密码卡片 -->
        <el-card class="password-card">
          <template #header>
            <div class="card-header">
              <span>修改密码</span>
            </div>
          </template>
          
          <el-form 
            ref="passwordFormRef" 
            :model="passwordForm" 
            :rules="passwordRules"
            label-position="top"
          >
            <el-form-item prop="oldPassword" label="当前密码">
              <el-input 
                v-model="passwordForm.oldPassword" 
                type="password"
                placeholder="请输入当前密码"
                show-password
              ></el-input>
            </el-form-item>
            <el-form-item prop="newPassword" label="新密码">
              <el-input 
                v-model="passwordForm.newPassword" 
                type="password"
                placeholder="请输入新密码"
                show-password
              ></el-input>
            </el-form-item>
            <el-form-item prop="confirmPassword" label="确认新密码">
              <el-input 
                v-model="passwordForm.confirmPassword" 
                type="password"
                placeholder="请再次输入新密码"
                show-password
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="changePasswordAction" :loading="passwordLoading">确认修改</el-button>
              <el-button @click="resetPasswordForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="18">
        <!-- 车辆管理卡片 -->
        <el-card class="vehicle-card">
          <template #header>
            <div class="card-header">
              <span>车辆管理</span>
              <el-button type="primary" @click="showAddVehicleDialog">添加车辆</el-button>
            </div>
          </template>
          
          <div v-if="vehicles.length > 0">
            <el-table :data="vehicles" style="width: 100%">
              <el-table-column prop="plateNumber" label="车牌号" width="120"></el-table-column>
              <el-table-column prop="vehicleBrand" label="品牌"></el-table-column>
              <el-table-column prop="vehicleModel" label="型号"></el-table-column>
              <el-table-column prop="vehicleType" label="类型"></el-table-column>
              <el-table-column prop="vehicleColor" label="颜色"></el-table-column>
              <el-table-column label="默认车辆" width="100">
                <template #default="scope">
                  <el-tag type="success" v-if="scope.row.isDefault === 1">默认</el-tag>
                  <el-button 
                    v-else 
                    type="primary" 
                    link
                    @click="setDefaultVehicle(scope.row.id)"
                  >设为默认</el-button>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button 
                    type="primary" 
                    link
                    @click="showEditVehicleDialog(scope.row)"
                  >编辑</el-button>
                  <el-button 
                    type="danger" 
                    link
                    @click="confirmDeleteVehicle(scope.row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-empty v-else description="暂无车辆信息，请添加"></el-empty>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 添加/编辑车辆对话框 -->
    <el-dialog 
      v-model="vehicleDialogVisible" 
      :title="isEditVehicle ? '编辑车辆' : '添加车辆'"
      width="500px"
    >
      <el-form 
        ref="vehicleFormRef" 
        :model="vehicleForm" 
        :rules="vehicleRules"
        label-position="top"
      >
        <el-form-item prop="plateNumber" label="车牌号">
          <el-input v-model="vehicleForm.plateNumber" placeholder="请输入车牌号"></el-input>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="vehicleBrand" label="品牌">
              <el-input v-model="vehicleForm.vehicleBrand" placeholder="请输入品牌"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="vehicleModel" label="型号">
              <el-input v-model="vehicleForm.vehicleModel" placeholder="请输入型号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="vehicleType" label="类型">
              <el-select v-model="vehicleForm.vehicleType" placeholder="请选择车辆类型" style="width: 100%">
                <el-option label="小型轿车" value="小型轿车"></el-option>
                <el-option label="SUV" value="SUV"></el-option>
                <el-option label="MPV" value="MPV"></el-option>
                <el-option label="跑车" value="跑车"></el-option>
                <el-option label="皮卡" value="皮卡"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="vehicleColor" label="颜色">
              <el-select v-model="vehicleForm.vehicleColor" placeholder="请选择车辆颜色" style="width: 100%">
                <el-option label="白色" value="白色"></el-option>
                <el-option label="黑色" value="黑色"></el-option>
                <el-option label="红色" value="红色"></el-option>
                <el-option label="蓝色" value="蓝色"></el-option>
                <el-option label="银色" value="银色"></el-option>
                <el-option label="灰色" value="灰色"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item>
          <el-checkbox v-model="vehicleForm.isDefault" :true-label="1" :false-label="0">设为默认车辆</el-checkbox>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="vehicleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitVehicleForm" :loading="vehicleFormLoading">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getUserProfile, 
  updateUserProfile, 
  changePassword, 
  getUserVehicles, 
  addVehicle, 
  updateVehicle, 
  deleteVehicle 
} from '@/api/user'
import AppConfig from '@/config/app'

// 用户资料
const userProfile = ref({
  id: '',
  username: '',
  realName: '',
  phone: '',
  email: '',
  avatar: AppConfig.defaultAvatar,
  createdAt: ''
})
const editMode = ref(false)
const profileLoading = ref(false)
const profileFormRef = ref(null)
const profileForm = reactive({
  username: '',
  realName: '',
  phone: '',
  email: '',
  avatar: AppConfig.defaultAvatar
})

// 车辆管理
const vehicles = ref([])
const vehicleLoading = ref(false)
const vehicleDialogVisible = ref(false)
const vehicleFormRef = ref(null)
const vehicleFormLoading = ref(false)
const isEditVehicle = ref(false)
const currentVehicleId = ref(null)
const vehicleForm = reactive({
  plateNumber: '',
  vehicleBrand: '',
  vehicleModel: '',
  vehicleType: '',
  vehicleColor: '',
  isDefault: 0
})

// 修改密码
const passwordFormRef = ref(null)
const passwordLoading = ref(false)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 验证规则
// 手机号验证
const validatePhone = (rule, value, callback) => {
  const pattern = /^1[3-9]\d{9}$/
  if (value && !pattern.test(value)) {
    callback(new Error('请输入有效的11位手机号码'))
  } else {
    callback()
  }
}

// 邮箱验证
const validateEmail = (rule, value, callback) => {
  const pattern = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
  if (value && !pattern.test(value)) {
    callback(new Error('请输入有效的电子邮箱地址'))
  } else {
    callback()
  }
}

// 密码确认验证
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 车牌号验证
const validatePlateNumber = (rule, value, callback) => {
  const pattern = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{5,6}$/
  if (!pattern.test(value)) {
    callback(new Error('请输入有效的车牌号'))
  } else {
    callback()
  }
}

// 验证新密码不能与旧密码相同
const validateNewPassword = (rule, value, callback) => {
  if (value === passwordForm.oldPassword) {
    callback(new Error('新密码不能与当前密码相同'))
  } else {
    callback()
  }
}

// 个人信息验证规则
const profileRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2-20个字符之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { validator: validateEmail, trigger: 'blur' }
  ]
}

// 修改密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur' },
    { validator: validateNewPassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 车辆信息验证规则
const vehicleRules = {
  plateNumber: [
    { required: true, message: '请输入车牌号', trigger: 'blur' },
    { validator: validatePlateNumber, trigger: 'blur' }
  ],
  vehicleBrand: [
    { required: true, message: '请输入品牌', trigger: 'blur' }
  ],
  vehicleModel: [
    { required: true, message: '请输入型号', trigger: 'blur' }
  ],
  vehicleType: [
    { required: true, message: '请选择车辆类型', trigger: 'change' }
  ],
  vehicleColor: [
    { required: true, message: '请选择车辆颜色', trigger: 'change' }
  ]
}

// 获取用户资料
const fetchUserProfile = async () => {
  try {
    const res = await getUserProfile()
    userProfile.value = res.data
    
    // 初始化表单数据
    profileForm.username = res.data.username
    profileForm.realName = res.data.realName
    profileForm.phone = res.data.phone
    profileForm.email = res.data.email
    profileForm.avatar = res.data.avatar
    profileForm.createdAt = res.data.createdAt
  } catch (error) {
    ElMessage.error('获取用户资料失败')
  }
}

// 获取车辆列表
const fetchVehicles = async () => {
  vehicleLoading.value = true
  try {
    const res = await getUserVehicles()
    vehicles.value = res.data
  } catch (error) {
    ElMessage.error('获取车辆列表失败')
  } finally {
    vehicleLoading.value = false
  }
}

// 更新个人资料
const updateProfile = async () => {
  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      profileLoading.value = true
      try {
        await updateUserProfile(profileForm)
        ElMessage.success('更新成功')
        editMode.value = false
        
        // 重新获取用户资料
        await fetchUserProfile()
      } catch (error) {
        ElMessage.error(error.message || '更新失败')
      } finally {
        profileLoading.value = false
      }
    }
  })
}

// 修改密码
const changePasswordAction = async () => {
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      passwordLoading.value = true
      try {
        await changePassword({
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword,
          confirmPassword: passwordForm.confirmPassword
        })
        ElMessage.success('密码修改成功')
        // 重置表单
        resetPasswordForm()
      } catch (error) {
        console.error('修改密码失败', error)
      } finally {
        passwordLoading.value = false
      }
    }
  })
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordFormRef.value.resetFields()
}

// 显示添加车辆对话框
const showAddVehicleDialog = () => {
  isEditVehicle.value = false
  currentVehicleId.value = null
  vehicleForm.plateNumber = ''
  vehicleForm.vehicleBrand = ''
  vehicleForm.vehicleModel = ''
  vehicleForm.vehicleType = ''
  vehicleForm.vehicleColor = ''
  vehicleForm.isDefault = 0
  vehicleDialogVisible.value = true
}

// 显示编辑车辆对话框
const showEditVehicleDialog = (vehicle) => {
  isEditVehicle.value = true
  currentVehicleId.value = vehicle.id
  vehicleForm.plateNumber = vehicle.plateNumber
  vehicleForm.vehicleBrand = vehicle.vehicleBrand
  vehicleForm.vehicleModel = vehicle.vehicleModel
  vehicleForm.vehicleType = vehicle.vehicleType
  vehicleForm.vehicleColor = vehicle.vehicleColor
  vehicleForm.isDefault = vehicle.isDefault
  vehicleDialogVisible.value = true
}

// 提交车辆表单
const submitVehicleForm = async () => {
  await vehicleFormRef.value.validate(async (valid) => {
    if (valid) {
      vehicleFormLoading.value = true
      try {
        if (isEditVehicle.value) {
          // 编辑车辆
          await updateVehicle({
            id: currentVehicleId.value,
            ...vehicleForm
          })
          ElMessage.success('车辆信息更新成功')
        } else {
          // 添加车辆
          await addVehicle(vehicleForm)
          ElMessage.success('车辆添加成功')
        }
        
        vehicleDialogVisible.value = false
        // 重新获取车辆列表
        await fetchVehicles()
      } catch (error) {
        ElMessage.error(error.message || '操作失败')
      } finally {
        vehicleFormLoading.value = false
      }
    }
  })
}

// 设置默认车辆
const setDefaultVehicle = async (id) => {
  try {
    await updateVehicle({
      id,
      isDefault: 1
    })
    ElMessage.success('设置成功')
    // 重新获取车辆列表
    await fetchVehicles()
  } catch (error) {
    ElMessage.error(error.message || '设置失败')
  }
}

// 确认删除车辆
const confirmDeleteVehicle = (id) => {
  ElMessageBox.confirm('确定要删除该车辆吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteVehicle(id)
      ElMessage.success('删除成功')
      // 重新获取车辆列表
      await fetchVehicles()
    } catch (error) {
      ElMessage.error(error.message || '删除失败')
    }
  }).catch(() => {})
}

// 组件挂载时获取数据
onMounted(() => {
  fetchUserProfile()
  fetchVehicles()
})
</script>

<style scoped>
.user-profile {
  min-height: calc(100vh - 180px);
}

.page-header-card {
  margin-bottom: 20px;
  background: linear-gradient(135deg, #3f51b5, #3949ab);
  color: white;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title h2 {
  margin: 0;
  font-size: 24px;
}

.page-title p {
  margin: 8px 0 0;
  opacity: 0.8;
  font-size: 14px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.profile-card {
  margin-bottom: 20px;
}

.avatar-container {
  display: flex;
  justify-content: center;
  margin: 10px 0 20px;
}

.info-list {
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.info-label {
  color: #909399;
  font-size: 14px;
}

.info-value {
  font-weight: 500;
  color: #303133;
}

.password-card {
  margin-bottom: 20px;
}

.vehicle-card {
  margin-bottom: 20px;
  height: 100%;
}

@media screen and (max-width: 768px) {
  .vehicle-card {
    height: auto;
  }
}
</style> 